package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDto dto) {
        //1.检查参数  参数和登陆状态
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.获取收藏的行为信息，判断是否已经点过收藏，已经点过收藏，取消掉收藏
        //获取用户行为实体类
        ApBehaviorEntry byUserIdOrEquipmentId = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (byUserIdOrEquipmentId==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"获取行为实体信息失败");
        }
        Query query = Query.query(Criteria.where("entryId").is(byUserIdOrEquipmentId.getId()).and("articleId").is(dto.getArticleId()));
        ApCollection apCollection = mongoTemplate.findOne(query, ApCollection.class);
        //避免重复操作，如已经为收藏状态，传过来的参数仍是需要设置为收藏状态，则报异常
        if (dto.getOperation()==0&&apCollection!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"您已经设置过为收藏状态");
        }
        if (dto.getOperation().intValue() == 0) {
            apCollection =new ApCollection();
            apCollection.setEntryId(byUserIdOrEquipmentId.getId());
            apCollection.setArticleId(dto.getArticleId());
            apCollection.setType((short)0);
            apCollection.setCollectionTime(new Date());
            mongoTemplate.save(apCollection);
        } else {
            mongoTemplate.remove(query,ApCollection.class);
        }

        return ResponseResult.okResult();
    }
}
